import { yupResolver } from "@hookform/resolvers/yup";
import { ChangePassword } from "api/mutations";
import ConfirmAlert from "libs/confirmAlert";
import { useForm } from "react-hook-form";
import { useTranslation } from "react-i18next";
import { useMutation } from "react-query";
import { useNavigate } from 'react-router-dom';
import * as yup from "yup";
import { useState } from 'react';

// MUI Components
import {
  Grid,
  Typography,
  FormControl,
  FormHelperText,
  InputAdornment,
  useTheme
} from '@mui/material';

// MUI Icons
import LockIcon from '@mui/icons-material/Lock';
import VisibilityIcon from '@mui/icons-material/Visibility';
import VisibilityOffIcon from '@mui/icons-material/VisibilityOff';

// Styled Components
import {
  StyledPaper,
  StyledTextField,
  StyledAppButton
} from "components/objects/StyledComponents";

const schema = yup.object().shape({
  password: yup.string().min(8).required("editUserPage.passwordRequired"),
});

const EditUserPage = () => {
  const navigate = useNavigate();
  const { t } = useTranslation();
  const [showPassword, setShowPassword] = useState(false);
  const theme = useTheme();
  const isDarkMode = theme.palette.mode === 'dark';

  const {
    register,
    handleSubmit,
    formState: { errors }
  } = useForm({
    resolver: yupResolver(schema),
  });

  const mutation = useMutation(ChangePassword);

  const onSubmit = async (data) => {
    const response = await mutation.mutateAsync({ 
      password: data.password 
    });

    if (response) {
      ConfirmAlert.success(t("editUserPage.passwordUpdated"));
      navigate("/");
    }
  };

  const handleTogglePassword = () => {
    setShowPassword(!showPassword);
  };

  return (
    <Grid container justifyContent="center">
      <Grid item xs={12} sm={10} md={8} lg={6}>
        <StyledPaper darkMode={isDarkMode}>
          <Typography 
            component="h1" 
            variant="h5" 
            sx={{ mb: 3, pt: 2 }}
          >
            {t("editUserPage.changePassword")}
          </Typography>
          
          <Typography 
            variant="body1" 
            sx={{ mb: 4, opacity: 0.8 }}
          >
            {t("editUserPage.insertNewPassword")}
          </Typography>

          <form onSubmit={handleSubmit(onSubmit)}>
            <FormControl fullWidth sx={{ mb: 3 }}>
              <StyledTextField
                darkMode={isDarkMode}
                label={t("editUserPage.password")}
                type={showPassword ? "text" : "password"}
                fullWidth
                inputProps={{ maxLength: 256 }}
                {...register("password", { required: true })}
                error={!!errors.password}
                InputProps={{
                  startAdornment: (
                    <InputAdornment position="start">
                      <LockIcon />
                    </InputAdornment>
                  ),
                  endAdornment: (
                    <InputAdornment position="end">
                      <StyledAppButton
                        darkMode={isDarkMode}
                        aria-label="toggle password visibility"
                        onClick={handleTogglePassword}
                        sx={{ minWidth: 'auto', p: 1 }}
                      >
                        {showPassword ? <VisibilityOffIcon /> : <VisibilityIcon />}
                      </StyledAppButton>
                    </InputAdornment>
                  ),
                }}
              />
              {errors.password && (
                <FormHelperText error>
                  {t(errors.password.message)}
                </FormHelperText>
              )}
            </FormControl>

            <StyledAppButton
              darkMode={isDarkMode}
              type="submit"
              fullWidth
              variant="contained"
              sx={{ mt: 2, mb: 2, py: 1.5 }}
            >
              {t("editUserPage.updatePassword")}
            </StyledAppButton>
          </form>
        </StyledPaper>
      </Grid>
    </Grid>
  );
};

export default EditUserPage;